package com.ndp.fb.walle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ndp.ec.core.FbUserService;
import com.ndp.ec.core.ProductSetService;
import com.ndp.ec.core.UserService;
import com.ndp.fb.config.ConfigCentre;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.model.business.bo.nfs.NfsConfig;
import com.ndp.fb.model.business.vo.admanage.param.*;
import com.ndp.fb.model.business.vo.cache.result.EntrustAccountVo;
import com.ndp.fb.mongo.api.AccountAdImageMongoService;
import com.ndp.fb.mongo.api.AdImageMongoService;
import com.ndp.fb.mongo.api.TargetingService;
import com.ndp.fb.mongo.model.*;
import com.ndp.fb.rdb.api.AccountInstagramActRdbService;
import com.ndp.fb.rdb.model.AccountInstagramAct;
import com.ndp.fb.rdb.model.EntrustAccountExt;
import com.ndp.fb.rdb.model.FbUser;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.redis.api.RedisClient;
import com.ndp.fb.util.DateUtil;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.NFSUtil;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.business.*;
import com.ndp.fb.walle.model.bo.adresource.AdVideoBo;
import com.ndp.fb.walle.model.bo.connectionobject.ConnectionObjectBo;
import com.ndp.fb.walle.model.bo.productconfiguration.result.ProductConfigurationBo;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.adpublishcondition.param.AccountFromConnParam;
import com.ndp.fb.walle.model.vo.adpublishcondition.result.AdPublishConditionDetailResult;
import com.ndp.fb.walle.util.ResponseUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author giser.yang
 * @Title: AdGroupStatsController.java
 * @Copyright: Copyright © 2015
 * @Description:
 * @Company: yeahmobi
 * @Created on 下午12:01:07
 */
@RequestMapping("/admanage")
@Controller
public class AdManageController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Reference
    private FbUserService fbUserService;
    @Autowired
    AdManageService adManageService;
    @Autowired
    AdGroupService adGroupService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private AdPublishConditionService adPublishConditionService;
    @Reference
    UserService userService;
    @Reference
    AdImageMongoService adImageMongoService;
    @Reference
    AccountAdImageMongoService accountAdImageMongoService;
    @Reference
    ProductSetService productSetService;
    @Autowired
    private NFSUtil nfsUtil;
    @Autowired
    private NfsConfig nfsConfig;
    @Reference
    TargetingService targetingService;
    @Reference
    private AccountInstagramActRdbService accountInstagramActRdbService;

    @Autowired
    AdVideoService adVideoService;
    @Autowired
    ConnectionObjectService connectionObjectService;
    @Autowired
    ProductConfigurationService productConfigurationService;
    @Autowired
    AdPublishAppAccountCPAService adPublishAppAccountCPAService;

    @Autowired
    private EntrustAccountService entrustAccountService;

    /**
     * 根据adset进行分组展示广告
     *
     * @param param 查询参数
     * @return 分组后的返回结果
     */
    @RequestMapping(value = "groupbyadset")
    @ResponseBody
    public ResponseEntity<String> groupByAdset(
            @RequestParam(value = "param", required = true) String param) {
        logger.info("AdManageController groupbyadset() begin.");
        try {
            // 先初始化一个空结果，避免前端出错
            HashMap<String, Object> summary = new HashMap<>();
            summary.put("adCount", 0);
            summary.put("adSetCount", 0);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("summary", summary);
            dataMap.put("adSets", new ArrayList<>());
            Map<String, Object> data = new HashMap<String, Object>();

            GroupByAdSetParam groupByAdSetParam = JSON.parseObject(param, GroupByAdSetParam.class);
            Map<String, Object> groupByAdSetResult = adManageService.groupByAdset(groupByAdSetParam);
            if (null != groupByAdSetResult) {
                dataMap = groupByAdSetResult;
            }
            data.putAll(dataMap);
            setAdGroupStatsRefreshDatetime(data);//设置数据刷新时间
            OutputResult outputResult = ResponseUtils.bulidOutputResult(null, data);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (Exception e) {
            logger.error(
                    "AdManageController groupbyadset() error"
                            + e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(ErrorType.BUSINESS_EXCEPTION, null);
        logger.info("AdGroupStatsController groupbyadset() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    @RequestMapping(value = "graphbyday")
    @ResponseBody
    public ResponseEntity<String> graphByDay(
            @RequestParam(value = "param", required = true) String param) {
        logger.info("AdManageController graphByDay() begin.");
        try {
            Map<String, Object> dataMap = adManageService.graphByDay(JSON.parseObject(param, GroupByDayParam.class));
            OutputResult outputResult = ResponseUtils.bulidOutputResult(null, dataMap);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (Exception e) {
            logger.error("AdGroupStatsController graphByDay() error" + e.getMessage(), e);
        } finally {
            logger.info("AdGroupStatsController graphByDay() end.");
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(ErrorType.BUSINESS_EXCEPTION, null);
        logger.info("AdGroupStatsController graphByDay() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 得到 AdGroupStats 数据刷新时间
     *
     * @param data
     */
    private void setAdGroupStatsRefreshDatetime(Map<String, Object> data) {
        try {
            if (data == null) {
                return;
            }
            String refreshDatetime = (String) redisClient.get(CommonConstants.ADGROUP_STATS_INCREMENT_CRON_REFRESH_DATETIME);
            if (StringUtil.isNotEmpty(refreshDatetime)) {
                data.put("refreshDatetime", refreshDatetime);
            }
        } catch (Exception e) {
            logger.error("获取 AdGroupStats 数据刷新时间失败!");
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 更新广告
     *
     * @param param 查询参数
     * @return 分组后的返回结果
     */
    @RequestMapping(value = "updateAd")
    @ResponseBody
    public ResponseEntity<String> updateAd(
            @RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("AdManageController updateAd() begin.");
        try {
            User user = (User) request.getSession().getAttribute("user");
            FbUser fbUser = fbUserService.getFbUser(user.getTicket());
            UpdateAdParam updateAdParam = JSON.parseObject(param, UpdateAdParam.class);
            String job_id = adGroupService.createAdGroupJob(updateAdParam.getAd_id(), fbUser.getAccessToken(), updateAdParam.getValue(), updateAdParam.getJob_type());
            JSONObject job = new JSONObject();
            job.put("job_id", job_id);
            OutputResult outputResult = ResponseUtils.bulidOutputResult(null, job);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (Exception e) {
            logger.error(
                    "AdManageController updateAd() error"
                            + e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(ErrorType.BUSINESS_EXCEPTION, null);
        logger.info("AdManageController updateAd end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 更新广告
     *
     * @param param 查询参数
     * @return 分组后的返回结果
     */
    @RequestMapping(value = "updateAdSet")
    @ResponseBody
    public ResponseEntity<String> updateAdSet(
            @RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("AdManageController updateAdSet() begin.");
        try {
            User user = (User) request.getSession().getAttribute("user");
            FbUser fbUser = fbUserService.getFbUser(user.getTicket());
            UpdateAdSetParam updateAdParam = JSON.parseObject(param, UpdateAdSetParam.class);
            String job_id = adGroupService.createAdSetJob(updateAdParam.getAdSet_id(), fbUser.getAccessToken(), updateAdParam.getValue(), updateAdParam.getJob_type());
            JSONObject job = new JSONObject();
            job.put("job_id", job_id);
            OutputResult outputResult = ResponseUtils.bulidOutputResult(null, job);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (Exception e) {
            logger.error(
                    "AdManageController updateAdSet() error"
                            + e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(ErrorType.BUSINESS_EXCEPTION, null);
        logger.info("AdManageController updateAdSet end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 获取JOB状态
     *
     * @param param 查询参数
     * @return 分组后的返回结果
     */
    @RequestMapping(value = "getJob")
    @ResponseBody
    public ResponseEntity<String> getJob(
            @RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("AdManageController getJob() begin.");
        try {
            User user = (User) request.getSession().getAttribute("user");
            FbUser fbUser = fbUserService.getFbUser(user.getTicket());
            JobParam updateAdParam = JSON.parseObject(param, JobParam.class);
            FaceBookJob job = adGroupService.getAdGroupJob(updateAdParam.getJob_id());
            OutputResult outputResult = ResponseUtils.bulidOutputResult(null, job);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (Exception e) {
            logger.error(
                    "AdManageController getJob() error"
                            + e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(ErrorType.BUSINESS_EXCEPTION, null);
        logger.info("AdManageController getJob end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 获取单个广告
     *
     * @param param 查询参数
     * @return 分组后的返回结果
     */
    @RequestMapping(value = "getAd")
    @ResponseBody
    public ResponseEntity<String> getAd(
            @RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("AdManageController getAd() begin.");
        try {
            JSONObject ad = JSON.parseObject(param);
            AdForMongo adForMongo = adGroupService.findAdForMongo(ad.getLongValue("ad_id"), null);
            if (adForMongo.getAdSet().getEnd_utc_time() == null && StringUtils.isNotBlank(adForMongo.getAdSet().getEnd_time())) {
                adForMongo.getAdSet().setEnd_utc_time(DateUtil.FbDateToJavaDate(adForMongo.getAdSet().getEnd_time()).getTimeInMillis());
            }
            AdCreativeForMongo adCreativeForMongo = adForMongo.getCreative();
            String local_picture_url = null;
            JSONObject story = JSONObject.parseObject(adCreativeForMongo.getObject_story_spec());
            if (story.containsKey("link_data")) {
                if (story.getJSONObject("link_data").containsKey("image_hash")) {
                    String image_hash = story.getJSONObject("link_data").getString("image_hash");
                    if (StringUtils.isNotBlank(image_hash)) {
                        local_picture_url = getLocalUrlByImageHash(image_hash);
                        story.put("local_picture_url", local_picture_url);
                    }
                } else if (story.getJSONObject("link_data").containsKey("picture")) {
                    String picture = story.getJSONObject("link_data").getString("picture");
                    local_picture_url = getLocalUrlByPicture(picture);
                    story.put("local_picture_url", local_picture_url);
                }

                if (story.getJSONObject("link_data").containsKey("child_attachments")) {
                    JSONArray child_attachments = story.getJSONObject("link_data").getJSONArray("child_attachments");
                    for (int i = 0; i < child_attachments.size(); i++) {
                        JSONObject child_attachment = child_attachments.getJSONObject(i);
                        if (child_attachment.containsKey("image_hash")) {
                            String image_hash = child_attachment.getString("image_hash");
                            if (StringUtils.isNotBlank(image_hash)) {
                                local_picture_url = getLocalUrlByImageHash(image_hash);
                                child_attachment.put("local_picture_url", local_picture_url);
                            }
                        } else if (child_attachment.containsKey("picture")) {
                            String picture = child_attachment.getString("picture");
                            local_picture_url = getLocalUrlByPicture(picture);
                            story.put("local_picture_url", local_picture_url);
                        }
                    }
                }
            }
            if (story.containsKey("video_data")) {
                String image_hash = story.getJSONObject("video_data").getString("image_hash");
                if (StringUtils.isNotBlank(image_hash)) {
                    local_picture_url = getLocalUrlByImageHash(image_hash);
                    story.put("local_picture_url", local_picture_url);
                }
                if (StringUtils.isBlank(story.getString("local_picture_url"))) {
                    String image_url = story.getJSONObject("video_data").getString("image_url");
                    if (StringUtils.isNotBlank(image_url)) {
                        local_picture_url = getLocalUrlByPicture(image_url);
                        story.put("local_picture_url", local_picture_url);
                    }
                }
                String video_id = story.getJSONObject("video_data").getString("video_id");
                String local_video_url = getLocalVideoUrlByVideoId(video_id);
                story.put("local_video_url", local_video_url);
            }
            adCreativeForMongo.setObject_story_spec(JSON.toJSONString(story));
            OutputResult outputResult = ResponseUtils.bulidOutputResult(null, adForMongo);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (Exception e) {
            logger.error(
                    "AdManageController getAd() error"
                            + e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(ErrorType.BUSINESS_EXCEPTION, null);
        logger.info("AdManageController getAd end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    private String getLocalUrlByImageHash(String image_hash) {
        AccountAdImageMongo accountAdImageMongo = accountAdImageMongoService.getAccountAdImageMongobyImageHash(image_hash);
        if (accountAdImageMongo != null) {
            return nfsConfig.getFullAddress() + CommonConstants.SYMBOL_SLASH + accountAdImageMongo.getLocalUrl();
        }
        Image image = adImageMongoService.findOneByHash(image_hash);
        if (image != null) {
            if (StringUtils.isBlank(image.getUrl()) || image.getUrl().indexOf("null") > 0) {
                String localUrl = getLocalUrlByPicture(image.getPicture());
                if (StringUtils.isNotBlank(localUrl)) {
                    adImageMongoService.updateAdImageUrlByHash(image_hash, localUrl);
                }
                return localUrl;
            } else {
                return getLocalUrlByPicture(image.getUrl());
            }
        }
        return null;
    }

    private String getLocalUrlByPicture(String picture) {
        try {
            String nfsfbvisitDomain = ConfigCentre.getString("nfs.fb.visit.domain", "adimage.clientgear.com");
            String nfsDomain = ConfigCentre.getString("nfs.config.domain", "fbfile.clientgear.com");
            if (picture.contains(nfsfbvisitDomain)) {
                return picture.replace(nfsfbvisitDomain, nfsDomain);
            }
            return nfsConfig.getFullAddress() + CommonConstants.SYMBOL_SLASH + nfsUtil.uploadToNFS(picture, false);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    private String getLocalVideoUrlByVideoId(String fbVideoId) {
        try {
            AdVideoBo adVideoBo = adVideoService.getAdvideoByFbVideoId(fbVideoId);
            if (adVideoBo != null) {
                return adVideoBo.getVisitPath();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取单个广告
     *
     * @param param 查询参数
     * @return 分组后的返回结果
     */
    @RequestMapping(value = "getAdSet")
    @ResponseBody
    public ResponseEntity<String> getAdSet(
            @RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("AdManageController getAdSet() begin.");
        try {
            User user = (User) request.getSession().getAttribute("user");
            String lan = user.getLanguage();
            lan = lan.split(CommonConstants.SYMBOL_LINE)[0] + CommonConstants.SYMBOL_UNDERLINE + lan.split(CommonConstants.SYMBOL_LINE)[1].toUpperCase();
            JSONObject ad = JSON.parseObject(param);
            AdSetForMongo adForMongo = adGroupService.findAdSetForMongo(ad.getLongValue("adSet_id"), null);
            if (adForMongo.getEnd_utc_time() == null && StringUtils.isNotBlank(adForMongo.getEnd_time())) {
                adForMongo.setEnd_utc_time(DateUtil.FbDateToJavaDate(adForMongo.getEnd_time()).getTimeInMillis());
            }
            Map<String, Object> map = new HashMap<>();
            map.put("adSet", adForMongo);
            JSONObject app = JSONObject.parseObject(adForMongo.getPromoted_object());
            if (app != null) {
                if (app.containsKey("application_id")) {
                    Long appId = app.getLongValue("application_id");
                    String url = app.getString("object_store_url");
                    String platform = "";
                    if (url.contains("play.google.com")) {
                        platform = "google_play";
                        AdPublishConditionDetailResult adPublishConditionDetailResult = adPublishConditionService.getAdPublishConditionDetailResult(user.getTicket(), appId, platform);
                        if (adPublishConditionDetailResult != null) {
                            map.put("condition", adPublishConditionDetailResult);
                        }
                    } else if (url.contains("itunes.apple.com")) {
                        platform = "itunes";
                        AdPublishConditionDetailResult adPublishConditionDetailResult = adPublishConditionService.getAdPublishConditionDetailResult(user.getTicket(), appId, platform);
                        if (adPublishConditionDetailResult != null) {
                            map.put("condition", adPublishConditionDetailResult);
                        }
                    }
                    ProductConfigurationBo productConfigurationBo = productConfigurationService.findByFbConnectionObjectIdAndPlatForm(appId, platform);
                    if (productConfigurationBo != null) {
                        map.put("cpa_support", adPublishAppAccountCPAService.isSupportCPA(adForMongo.getAccount_id(), productConfigurationBo.getId(), appId));
                    }
                    //获取应用的ID
                    ConnectionObjectBo connectionObjectBo = connectionObjectService.findByFbConnectionObjectIdAndType(appId, 2);
                    map.put("app", connectionObjectBo);
                }
            }
            JSONObject targeting = JSONObject.parseObject(adForMongo.getTargeting());
            if(targeting.containsKey("geo_locations")){
            	JSONObject geo_locations = targeting.getJSONObject("geo_locations");
            	if(geo_locations.containsKey("countries")){
            		JSONArray countries = geo_locations.getJSONArray("countries");
            		JSONArray countries_spec = new JSONArray();
            		String country = null;
            		for(int i=0;i<countries.size();i++){
            			country = countries.getString(i);
            			JSONObject country_spec = targetingService.getCountry(country,lan);
                        if(countries_spec != null) {
                            country_spec.put("name", country_spec.getString(lan+CommonConstants.SYMBOL_UNDERLINE+"name"));
                            country_spec.remove(country_spec.getString(lan+CommonConstants.SYMBOL_UNDERLINE+"name"));
                            countries_spec.add(country_spec);
                        }
            		}
            		geo_locations.put("countries", countries_spec);
            	}
            }
            if(targeting.containsKey("excluded_geo_locations")){
            	JSONObject geo_locations = targeting.getJSONObject("excluded_geo_locations");
            	if(geo_locations.containsKey("countries")){
            		JSONArray countries = geo_locations.getJSONArray("countries");
            		JSONArray countries_spec = new JSONArray();
            		String country = null;
            		for(int i=0;i<countries.size();i++){
            			country = countries.getString(i);
            			JSONObject country_spec = targetingService.getCountry(country,lan);
                        if(countries_spec != null) {
                            country_spec.put("name", country_spec.getString(lan+CommonConstants.SYMBOL_UNDERLINE+"name"));
                            country_spec.remove(country_spec.getString(lan+CommonConstants.SYMBOL_UNDERLINE+"name"));
                            countries_spec.add(country_spec);
                        }
            		}
            		geo_locations.put("countries", countries_spec);
            	}
            }
            if(targeting.containsKey("locales")){
            	JSONArray locales = targeting.getJSONArray("locales");
            	JSONArray locales_spec = new JSONArray();
            	Integer key = null;
        		for(int i=0;i<locales.size();i++){
        			key = locales.getInteger(i);
        			JSONObject locale = targetingService.getLocale(key, lan);
                    if(locale != null) {
                        locale.put("name", locale.getString(lan));
                        locales_spec.add(locale);
                    }
        		}
        		targeting.put("locales", locales_spec);
            }
            if(targeting.containsKey("user_device")){
            	JSONArray user_devices = targeting.getJSONArray("user_device");
            	JSONArray user_devices_spec = new JSONArray();
            	String name = null;
        		for(int i=0;i<user_devices.size();i++){
        			name = user_devices.getString(i);
        			JSONObject locale = targetingService.getUserDevice(name, lan);
                    if(locale != null) {
                        if(locale.getJSONObject(lan) != null)
                            locale.put("description", locale.getJSONObject(lan).getString("description"));
                        locale.remove(lan);
                        user_devices_spec.add(locale);
                    }
        		}
        		targeting.put("user_device", user_devices_spec);
            }
            JSONArray productAudienceSpecs = targeting.getJSONArray("product_audience_specs");
            if (null != productAudienceSpecs) {
                productAudienceSpecs.forEach(productAudienceSpec -> {
                    String productSetId = ((JSONObject) productAudienceSpec).getString("product_set_id");
                    if (StringUtils.isNotEmpty(productSetId)) {
                        JSONObject productSet = productSetService.findByFbProductSetId(NumberUtils.toLong(productSetId));
                        String name = "";
                        if (StringUtils.isNotEmpty(productSet.getString("name"))) {
                            name = productSet.getString("name");
                        }
                        ((JSONObject) productAudienceSpec).put("product_set_name", name);
                    }
                });
            }
            map.put("targeting_spec", targeting);
            List<AccountInstagramAct> accountInstagramActs = accountInstagramActRdbService.queryInsActByAccount(adForMongo.getAccount_id());
            if (CollectionUtils.isEmpty(accountInstagramActs)) {
                map.put("instagram_support", false);
            } else {
                map.put("instagram_support", true);
            }

            //              
            OutputResult outputResult = ResponseUtils.bulidOutputResult(null, map);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (Exception e) {
            logger.error(
                    "AdManageController getAdSet() error"
                            + e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(ErrorType.BUSINESS_EXCEPTION, null);
        logger.info("AdManageController getAdSet end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    @RequestMapping(value = "getAccounts")
    @ResponseBody
    public ResponseEntity<String> getAccounts(@RequestParam(value = "param", required = true) String param, HttpServletRequest httpServletRequest) {
        logger.info("AdPublishConditionController getAccounts() begin.");
        ErrorType errorType = null;
        List<EntrustAccountVo> data = new ArrayList<>();
        try {
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            AccountFromConnParam accountFromConnParam = JSON.parseObject(param, AccountFromConnParam.class);
            List<EntrustAccountExt> entrustAccounts;
            if (accountFromConnParam != null && accountFromConnParam.isOutLink()) {
                entrustAccounts = entrustAccountService.findEntrustAccountsByUserIdAndConnObjId(user.getTicket(), accountFromConnParam.getConnObjId());
            } else {
                entrustAccounts = entrustAccountService.findEntrustAccountsByfbConnectionObjectIdAndUserId(accountFromConnParam.getConnObjId(), user.getTicket());
            }
            Set<Long> accountIds = new HashSet<>();
            //在这里 去个重
            if (!CollectionUtils.isEmpty(entrustAccounts)) {
                EntrustAccountExt ad = null;
                int size = entrustAccounts.size();
                for (int i = size - 1; i >= 0; i--) {
                    ad = entrustAccounts.get(i);
                    if (!accountIds.contains(ad.getFbAccountId())) {
                        accountIds.add(ad.getFbAccountId());
                    } else {
                        entrustAccounts.remove(i);
                    }
                }
            }
            if (ListUtil.isNotEmpty(entrustAccounts)) {
                data = getEntrustAccountVo(entrustAccounts);
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("AdPublishConditionController getAccounts() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSON(outputResult).toString());
    }

    private List<EntrustAccountVo> getEntrustAccountVo(List<EntrustAccountExt> entrustAccounts) {
        List<EntrustAccountVo> voList = new ArrayList<>();
        EntrustAccountVo entrustAccountVo;
        for (EntrustAccountExt entrustAccount : entrustAccounts) {
            entrustAccountVo = new EntrustAccountVo();
            entrustAccountVo.setId(entrustAccount.getId());
            String displayName = entrustAccount.getEmail() != null ? entrustAccount.getEmail() : (entrustAccount.getName() != null ? entrustAccount.getName() : entrustAccount.getFbAccountId() + "");
            entrustAccountVo.setDisplayName(displayName);
            entrustAccountVo.setFbAccountId(entrustAccount.getFbAccountId());
            entrustAccountVo.setStatus(entrustAccount.getStatus());
            entrustAccountVo.setRole(entrustAccount.getRole());
            entrustAccountVo.setFbUserId(entrustAccount.getFbUserId());
            entrustAccountVo.setTimezone(entrustAccount.getTimezone());
            entrustAccountVo.setOffset(entrustAccount.getTimezoneOffset());
            voList.add(entrustAccountVo);
        }
        return voList;
    }
}
